package database.rescue;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import database.PrepareFiles;

public class GetBlogDatabase {
	private String login; 
	
	public GetBlogDatabase(String login) {
		this.login = login;
	}
	
	public List<Properties> getBlogs() throws IOException {
		return getBlogsFromFile();
	}
	
	public void removeAll() {
		File file = new File(getPath());
		for (File f : file.listFiles()){
			if(!f.getName().equals(login + ".xml") && !f.isDirectory()){
				f.delete();
			}
		}
	}
	
	public void remove(String title) {
		File file = new File(getPath()+title.trim().replace(" ", "_") + ".xml");
		file.delete();
	}
	
	private List<Properties> getBlogsFromFile() throws IOException {
		List<Properties> blogs = new LinkedList<Properties>();
		File file = new File(getPath());
		for (File f : file.listFiles()){
			if(!f.getName().equals(login + ".xml") && !f.isDirectory()){
				blogs.add(loadFromFile(f));
			}
		}
		return blogs;
	}
	
	private Properties loadFromFile(File file) throws IOException {
		Properties prop = new Properties();
		
		PrepareFiles.prepareFile(file.getAbsolutePath());
		FileInputStream in = new FileInputStream(file);
		prop.loadFromXML(in);
		in.close();
		
		return prop;
	}
	
	private String getPath() {
		return "Database/"+login + "/";
	}
}
